package com.webwork.project.system.controller;

import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import com.alibaba.fastjson.JSON;
import com.webwork.common.dataobject.DateFormat;
import com.webwork.common.util.RetUtil;

@Controller
public class LoginCtrl {
	
	private static final Logger log = LoggerFactory.getLogger(LoginCtrl.class);
	
	@Value("${system.title}")
	private String title;
	
	@GetMapping(value="/login")
	public String login(Model model) {
		model.addAttribute("title", title);
		return "login";
	}
	
//	@RequestMapping(value="/")
//	public String index() {
//		return "index";
//	}
	
	@PostMapping(value="/doLogin")
	public void doLogin(String username, String password, boolean rememberMe,
			HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
		// 修改编码格式
		httpServletResponse.setCharacterEncoding("utf-8");
		httpServletResponse.setContentType("application/json");

		if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
			String msg = "用户名或者密码不能为空";
			log.error(msg);
			this.responseFailure(httpServletResponse, msg);
		} else {
			Subject subject = SecurityUtils.getSubject();
			UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
			try {
				subject.login(token);
				log.info("{}于{}登录系统", username, DateFormat.Simple.format(new Date()));
				
				this.responseSuccess(httpServletRequest, httpServletResponse);
			} catch (AuthenticationException e) {
				String msg = "用户或密码错误";
				token.clear();
				if (e instanceof UnknownAccountException) {
					msg = "用户 ".concat(username).concat(" 不存在");
				} else if (e instanceof IncorrectCredentialsException) {
					msg = "密码不正确";
				} else {
	                msg = e.getMessage();
	            }
				log.error("登录异常:{}", msg);
				this.responseFailure(httpServletResponse, msg);
			}
		}
	}
	
	private void responseSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
		HttpSession session = httpServletRequest.getSession();
		// 删除缓存里的验证码信息
		session.removeAttribute("captcha");
		RetUtil result = RetUtil.success().message("登录成功");
		// 输出结果
		httpServletResponse.getWriter().write(JSON.toJSONString(result));
	}
	
	private void responseFailure(HttpServletResponse httpServletResponse, String msg) throws IOException {
		httpServletResponse.getWriter().write(JSON.toJSONString(RetUtil.fail().message(msg)));
	}
	
//	@PostMapping(value="/doLogin")
//	public ModelAndView subLogin(String username, String password, boolean rememberMe) {
//		ModelAndView view = new ModelAndView();
//		if (StrUtil.isEmpty(username) || StrUtil.isEmpty(password)) {
//			view.getModelMap().addAttribute("title", title);
//			view.getModelMap().addAttribute("msg", "用户名或者密码不能为空");
//			view.setViewName("login");
//		} else {
//			Subject subject = SecurityUtils.getSubject();
//			UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
//			try {
//				subject.login(token);
//				log.info("{}于{}登录系统", username, DateFormat.Simple.format(new Date()));
//				view.setView(new RedirectView("/manager"));
//			} catch (AuthenticationException e) {
//				String msg = "用户或密码错误";
//				token.clear();
//				if (e instanceof UnknownAccountException) {
//					msg = "用户 ".concat(username).concat(" 不存在");
//					log.error(msg, e);
//				} else if (e instanceof IncorrectCredentialsException) {
//					msg = "密码不正确";
//					log.error(msg, e);
//				} else {
//	                msg = e.getMessage();
//	                log.error("登录异常:", e);
//	            }
//				view.getModelMap().addAttribute("title", title);
//				view.getModelMap().addAttribute("msg", msg);
//				view.setViewName("login");
//			}
//		}
//		return view;
//	}
	
}
